package com.frxuexi.report.view

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil3.compose.AsyncImage
import com.frxuexi.lib_base.BaseTitle
import com.frxuexi.lib_base.R
import com.frxuexi.lib_base.RoutePath
import com.frxuexi.lib_base.UiState
import com.frxuexi.report.ReportEntity
import com.frxuexi.report.ReportIntent
import com.frxuexi.report.ReportViewModel
import com.google.gson.Gson
import com.king.ultraswiperefresh.UltraSwipeRefresh
import com.king.ultraswiperefresh.rememberUltraSwipeRefreshState
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

data class ReportData(val type:Int,val content:String,val title:String )

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ReportListPage(navHostController: NavHostController,vm:ReportViewModel= hiltViewModel()) {
    var list = remember {
        SnapshotStateList<ReportEntity>()
    }
    val state = rememberUltraSwipeRefreshState()
    var page by remember {
        mutableStateOf(1)
    }

    var isShow by remember {
        mutableStateOf(false)
    }
    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        list.addAll(it.data as Collection<ReportEntity>)
                    }

                    else -> {}
                }
            }
        }
        vm.sendIntent(ReportIntent.getReports(mapOf("userId" to 1,"page" to 1)))
    })

    LaunchedEffect(key1 = state.isRefreshing, block = {
        if(state.isRefreshing){
            if(page!=1){
                list.clear()
            }
            page=1
            vm.sendIntent(ReportIntent.getReports(mapOf("userId" to 1,"page" to 1)))
            state.isRefreshing=false
        }
    })

    LaunchedEffect(key1 = state.isLoading, block = {
        if(state.isLoading){
            page++
            vm.sendIntent(ReportIntent.getReports(mapOf("userId" to 1,"page" to page)))
            state.isLoading=false
        }
    })

    Scaffold(floatingActionButton = {
        Image(painter = painterResource(id = R.drawable.icon159), contentDescription ="",
            Modifier.clickable {
                isShow=true
            })
    }) {
        Column(Modifier.padding(it)) {
            BaseTitle(title = "工作日志", navHostController = navHostController)
            UltraSwipeRefresh(state = state, onRefresh = { state.isRefreshing=true }, onLoadMore = { state.isLoading=true }) {
                LazyColumn(verticalArrangement = Arrangement.spacedBy(15.dp),content = {
                    items(list){
                        ReportItem(entity = it)
                    }
                })
            }
        }
    }
    
    if(isShow){
        val datas = listOf<ReportData>(
            ReportData(1, "1", "日报"),
            ReportData(2, "7", "周报"),
            ReportData(3, "30", "月报"),
            ReportData(4, "季度", "季度报表"),
            ReportData(5, "业绩", "业绩报表"),
            ReportData(6, "营业", "营业财报")
        )
        AlertDialog(onDismissRequest = { isShow = false }) {
            Column(Modifier.fillMaxWidth().background(Color.White, RoundedCornerShape(20.dp)).padding(20.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
                Text(text = "新建汇报", fontSize = 22.sp, fontWeight = FontWeight.Bold)
                LazyVerticalGrid(columns = GridCells.Fixed(3), content = {
                    items(datas){
                        DialogItem(data = it,navHostController){
                            isShow=false
                        }
                    }
                })
            }
        }
    }
}

@Composable
fun DialogItem(data: ReportData,navHostController: NavHostController, onClick: () -> Unit){
    Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.clickable {
        val json = Gson().toJson(data)
        navHostController.navigate(RoutePath.REPORT+"/$json")
        onClick()
    }) {
        Column(modifier = Modifier.size(60.dp).background(colorResource(id = R.color.lightblue), CircleShape)
            .padding(8.dp).border(1.dp, Color.Blue, RoundedCornerShape(5.dp)).background(Color.White, RoundedCornerShape(5.dp)),
            verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
            Text(text = data.content)
        }

        Text(text = data.title)
    }
}

@Composable
fun ReportItem(entity: ReportEntity){
    Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(horizontal = 20.dp)) {
        Row {
            AsyncImage(model = "https://img0.baidu.com/it/u=797474174,3214837072&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1732294800&t=f472f47d1015da000b2194ee3b7a3c4a", contentDescription = "",
                modifier = Modifier
                    .size(50.dp)
                    .clip(CircleShape), contentScale = ContentScale.Crop)
            Spacer(modifier = Modifier.width(10.dp))
            Column(Modifier.height(50.dp), verticalArrangement = Arrangement.SpaceAround) {
                val type=if(entity.reportType==1)"日报" else if(entity.reportType==2)"周报"
                else if(entity.reportType==2)"月报" else if(entity.reportType==2)"季度报表"
                else if(entity.reportType==2)"业绩报表" else "营业财报"
                Text(text = type)
                val time = SimpleDateFormat("yyyy月MM日dd").format(entity.reportTime)
                Text(text = "$time 发布")
            }
        }
        Text(text = "今日内容：${entity.reportNowValue}")
        Text(text = "明日计划：${entity.reportNextValue}")
    }
}